package com.shop.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.common.ResponseResult;
import com.shop.entity.Category;
import com.shop.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    @GetMapping("/categories")
    public ResponseResult selectList(@RequestParam(required = false)Integer type,
                                     @RequestParam(required = false)Integer pagenum,
                                     @RequestParam(required = false)Integer pagesize){
        ResponseResult result=new ResponseResult();
        try{
            if (pagenum==null||pagesize==null){
                List<Category> list = categoryService.getListCategory(type);
                result.setSuccess("查询成功！",list);
            }else {
                Page<Category> pageCategory = categoryService.getPageCategory(type, pagenum, pagesize);
                result.setSuccess("查询成功！",pageCategory);
            }
        }catch (Exception e){
            result.setBADREQUEST(e.getMessage());
        }
        return result;
    }

    @ResponseBody
    @PostMapping("/categories")
    public ResponseResult add(@RequestBody Category category){
        ResponseResult result=new ResponseResult();
        Category category1=categoryService.selectByname(category.getCat_name());
        if (category1!=null){
            result.setUnprocesableentity("添加失败，此分类名称已经存在！");
            return result;
        }
        int add = categoryService.add(category);
        result.setSuccess("创建成功！",category);
        return result;
    }
    @ResponseBody
    @GetMapping("/categories/{id}")
    public ResponseResult findById(@PathVariable("id")Integer id){
        Category category=categoryService.findById(id);
        ResponseResult result=new ResponseResult();
        result.setSuccess("获取成功",category);
        return result;
    }

    @ResponseBody
    @PutMapping("categories/{id}")
    public ResponseResult update(@PathVariable("id")Integer id,
                                 @RequestBody Category category){
        categoryService.update(category);
        ResponseResult result=new ResponseResult();
        result.setSuccess("更新成功",category);
        return result;
    }

    @ResponseBody
    @DeleteMapping("/categories/{id}")
    public ResponseResult delete(@PathVariable("id")Integer id){
        categoryService.delete(id);
        ResponseResult result=new ResponseResult();
        result.setDELETED();
        return result;
    }
}
